import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'

const prisma = new PrismaClient()

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { email, password } = body

    console.log('Login attempt for email:', email)

    // 验证输入
    if (!email || !password) {
      console.log('Missing email or password')
      return NextResponse.json({ 
        success: false,
        error: '邮箱和密码都是必填项' 
      }, { status: 400 })
    }

    // 查找用户
    const user = await prisma.user.findUnique({
      where: { email: email.toLowerCase().trim() }
    })

    console.log('User found:', user ? 'Yes' : 'No')

    if (!user) {
      console.log('User not found')
      return NextResponse.json({ 
        success: false,
        error: '邮箱或密码错误' 
      }, { status: 401 })
    }

    // 验证密码
    const isValidPassword = await bcrypt.compare(password, user.password)
    console.log('Password valid:', isValidPassword)

    if (!isValidPassword) {
      console.log('Invalid password')
      return NextResponse.json({ 
        success: false,
        error: '邮箱或密码错误' 
      }, { status: 401 })
    }

    // 生成 JWT token
    const token = jwt.sign(
      { userId: user.id, email: user.email },
      process.env.JWT_SECRET || 'sheet_secret',
      { expiresIn: '7d' }
    )

    // 返回用户信息（不包含密码）
    const { password: _, ...userWithoutPassword } = user

    console.log('Login successful for user:', user.email)

    return NextResponse.json({ 
      success: true,
      user: userWithoutPassword,
      token,
      message: '登录成功' 
    })
  } catch (error) {
    console.error('Login error:', error)
    return NextResponse.json({ 
      success: false,
      error: '登录失败，请稍后重试' 
    }, { status: 500 })
  }
}
